import { Result } from '@/service/request/type';
import { AxiosProgressEvent } from 'axios';
export default () => {
    const percentage = ref(0);

    const upload = async (
        file: File,
        uploadData: { isUpdate: boolean },
        uploadFn: (
            params: any,
            uploadData: { isUpdate: boolean },
            onUploadProgress?: (e: AxiosProgressEvent) => void
        ) => Promise<Result>
    ) => {
        const data = await minUpload(file, uploadData, uploadFn);
        percentage.value = 0;
        return data;
    };

    const minUpload = async (
        file: File,
        uploadData: { isUpdate: boolean },
        uploadFn: (
            params: any,
            uploadData: { isUpdate: boolean },
            onUploadProgress?: (e: AxiosProgressEvent) => void
        ) => Promise<Result>
    ) => {
        const formData = new FormData();
        formData.append('file', file);
        const data = await uploadFn(formData, uploadData, (e: AxiosProgressEvent) => {
            percentage.value = Math.floor((e.loaded / (e.total || 0)) * 100);
        });
        return data;
    };

    return { percentage, upload };
};
